# 5.文件的读写
import win32file, win32api, win32con
import os


def SimpleFileDemo():
    testName = os.path.join(r"C:\Users\ASUS\Desktop", "opt_win_file.txt")

    if os.path.exists(testName):
        os.unlink(testName)  # os.unlink() 方法用于删除文件,如果文件是一个目录则返回一个错误。
    # 写
    handle = win32file.CreateFile(testName,
                                  win32file.GENERIC_WRITE,
                                  0,
                                  None,
                                  win32con.CREATE_NEW,
                                  0,
                                  None)
    test_data = "Hello0there".encode("ascii")
    win32file.WriteFile(handle, test_data)
    handle.Close()
    # 读
    handle = win32file.CreateFile(testName, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
    rc, data = win32file.ReadFile(handle, 1024)
    handle.Close()  # 此处也可使用win32file.CloseHandle(handle)来关闭句柄
    if data == test_data:
        print("Successfully wrote and read a file")
    else:
        raise Exception("Got different data back???")
    # 临时文件读写完后删除
    # os.unlink(testName)


if __name__ == '__main__':
    SimpleFileDemo()
    # print(win32api.GetTempPath())  # 获取临时文件夹路径